package com.cuixichang.minimalism.core.security.web;

import com.cuixichang.minimalism.core.security.core.*;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Stack;

public class MyAuthenticationEntryPoint implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e)
            throws IOException {
        httpServletResponse.setContentType("application/json;charset=UTF-8");
        Stack<ResponseChain> stack = new Stack<>();
        stack.push(new DefaultResponseChain());
        stack.push(new AccountExpiredChain());
        stack.push(new DisabledChain());
        stack.push(new BadCredentialsChain());
        stack.push(new UsernameNotFoundChain());
        stack.push(new LockedChain());
        boolean check;
        do {
            ResponseChain pop = stack.pop();
            check = pop.matching(e);
            if(check){
                pop.invoke(httpServletResponse, e);
            }
        } while (!stack.isEmpty() && !check);
    }
}
